package com.syni.mdd.yhd.common.all.service.impl.activity;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.activity.BmsUserOverMealDao;
import com.syni.mdd.yhd.common.all.dto.reponseDto.activity.UserReceRpDto;
import com.syni.mdd.yhd.common.all.dto.requestDto.BaseReDto;
import com.syni.mdd.yhd.common.all.entity.BmsDxClientRole;
import com.syni.mdd.yhd.common.all.entity.BmsMealUserHelp;
import com.syni.mdd.yhd.common.all.entity.activity.BmsMealPrize;
import com.syni.mdd.yhd.common.all.entity.activity.BmsMealPrizeRecord;
import com.syni.mdd.yhd.common.all.entity.activity.BmsUserOverMeal;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsFullCoupon;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsUserReceCoupon;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.entity.user.BmsUserBlacklist;
import com.syni.mdd.yhd.common.all.enums.ActivityEnums;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.service.activity.BmsMealPrizeRecordService;
import com.syni.mdd.yhd.common.all.service.activity.BmsMealPrizeService;
import com.syni.mdd.yhd.common.all.service.activity.BmsMealUserHelpService;
import com.syni.mdd.yhd.common.all.service.activity.OverMealService;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.service.user.BmsUserBlacklistService;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.yhd.common.all.utils.activity.LotteryUtil;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;;
import lombok.extern.log4j.Log4j2;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @className
 * @description TOO
 * @Author hwq
 * @DATE 2019/9/23 10:34
 * @VERSION 1.0
 **/
@Service
@Log4j2
public class OverMealServiceImpl extends BaseService<BmsUserOverMeal, Integer> implements OverMealService {

    private Object userHelp = new Object();

    @Autowired
    BmsUserOverMealDao bmsUserOverMealDao;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BmsMealPrizeService bmsMealPrizeService;

    @Autowired
    BmsMealPrizeRecordService bmsMealPrizeRecordService;

    @Autowired
    BmsVerRecordService bmsVerRecordService;

    @Autowired
    BmsUserReceCouponService bmsUserReceCouponService;

    @Autowired
    BmsFullCouponService bmsFullCouponService;

    @Autowired
    BmsMealUserHelpService bmsMealUserHelpService;

    @Autowired
    EntityManager entityManager;

    @Autowired
    BmsDxConfigService bmsDxConfigService;

    @Autowired
    BmsDxClientRoleService bmsDxClientRoleService;

    @Autowired
    BmsUserBlacklistService bmsUserBlacklistService;

    @Override
    public BmsUserOverMealDao getBaseDao() {
        return bmsUserOverMealDao;
    }

    @Override
    public Map<String, Object> openActivity(ParamsMap paramsMap) {
        if(redisTemplate.hasKey(Constants.REDIS_KEY_OVER_MEAL_OPEN)){
            String activityTime = redisTemplate.opsForValue().get(Constants.REDIS_KEY_OVER_MEAL_OPEN).toString();
            String[] startEndTime = activityTime.split(",");
            Integer startTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[0],DateTimeUtils.DATE_PATTERN_DAY_08));
            Integer endTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[1],DateTimeUtils.DATE_PATTERN_DAY_08));
            Integer nowTime = DateTimeUtils.getNowTimeStamp();
            if(nowTime >= startTime && nowTime < endTime) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("startTime", startEndTime[0]);
                resultMap.put("endTime", startEndTime[1]);
                //读取活动配置
                resultMap.put("config", bmsDxConfigService.getConfigByCode(BmsDxConfigService.MEAL_CODE));
                resultMap.put("shareUrl", JSON.parseObject(bmsDxConfigService.getConfigByCode(BmsDxConfigService.MEAL_CODE)).get("shareUrl"));
                return ResultMapHelper.success(resultMap, "ok");
            }
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR,"no activity");
    }

    @Override
    public Map<String, Object> getOverlordMealData(ParamsMap paramsMap) {
        Integer userId = null;
        Map<String,Object> retMap = RequestParamUtils.checkAuthor(paramsMap);
        if(retMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(retMap.get("status"))){
            userId = Integer.parseInt(retMap.get("userIdentify").toString());
        }
        String pwd = paramsMap.getString("pwd");
        if(redisTemplate.hasKey(Constants.REDIS_KEY_OVER_MEAL_OPEN)){
            String activityTime = redisTemplate.opsForValue().get(Constants.REDIS_KEY_OVER_MEAL_OPEN).toString();
            String[] startEndTime = activityTime.split(",");
            Integer startTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[0],DateTimeUtils.DATE_PATTERN_DAY_08));
            Integer endTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[1],DateTimeUtils.DATE_PATTERN_DAY_08));
            Integer nowTime = DateTimeUtils.getNowTimeStamp();
            if(nowTime >= startTime && nowTime < endTime) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("startTime", startEndTime[0]);
                resultMap.put("endTime", startEndTime[1]);
                resultMap.put("config", bmsDxConfigService.getConfigByCode(BmsDxConfigService.MEAL_CODE));
                resultMap.put("shareUrl", JSON.parseObject(bmsDxConfigService.getConfigByCode(BmsDxConfigService.MEAL_CODE)).get("shareUrl"));
                resultMap.put("haveNum",userId == null ? 0 : this.findUserHaveNum(userId));
                if(redisTemplate.hasKey(Constants.REDIS_KEY_OVER_MEAL_PWD)){
                    String matchPwd = redisTemplate.opsForValue().get(Constants.REDIS_KEY_OVER_MEAL_PWD).toString();
                    if(pwd.equals(matchPwd) || pwd.equals(Constants.ACTIVITY_PWD)){
                        return ResultMapHelper.success(resultMap, "ok");
                    }
                }
            }
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR,"no activity");
    }

    private Integer findUserHaveNum(Integer userId) {
        Integer ret = 0;
        String redisKey = Constants.REDIS_KEY_USER_GET_MEAL_ACTIVITY + userId;
        boolean addLock = RedisTemplateUtils.addLockCanWait(redisKey,5);
        if(!addLock){
            return ret;
        }
        try {
            Date nowTime = new Date();
            BmsUserOverMeal bmsUserOverMeal = bmsUserOverMealDao.findByUserId(userId);
            if(bmsUserOverMeal == null){
                bmsUserOverMeal = new BmsUserOverMeal();
                bmsUserOverMeal.setUserId(userId);
                bmsUserOverMeal.setHaveNum(Integer.parseInt(redisTemplate.opsForValue().get(Constants.REDIS_KEY_OVER_MEAL_SNUM).toString()));
                bmsUserOverMeal.setNewTime(nowTime);
                bmsUserOverMealDao.save(bmsUserOverMeal);
            }
            if(bmsUserOverMeal.getExtraNum() == null){
                bmsUserOverMeal.setExtraNum(0);
            }
            ret = bmsUserOverMeal.getTodayNum() + bmsUserOverMeal.getExtraNum();
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally {
            RedisTemplateUtils.releaseLock(redisKey);
        }
        return ret;

    }

    @Override
    public Map<String, Object> smokeOverlordMeal(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        //Integer userId = Integer.parseInt(baseReDto.getUserId());
        String redisKey = Constants.REDIS_KEY_USER_ID + userId;
        Integer isFirstLogin = Constants.COMMON_FLAG_FALSE_INT;
        boolean addLock = RedisTemplateUtils.addLockCanWait(redisKey,5);
        if(!addLock){
            return ResultMapHelper.result(ActivityEnums.SYS_DELAY);
        }
        try {
            Date nowDate = new Date();
            if(!redisTemplate.hasKey(Constants.REDIS_KEY_OVER_MEAL_OPEN)) {
                return ResultMapHelper.result(ActivityEnums.ACTIVITY_CLOSE);
            }
            String activityTime = redisTemplate.opsForValue().get(Constants.REDIS_KEY_OVER_MEAL_OPEN).toString();
            String[] startEndTime = activityTime.split(",");
            Integer startTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[0],DateTimeUtils.DATE_PATTERN_DAY_08));
            Integer endTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[1],DateTimeUtils.DATE_PATTERN_DAY_08));
            Integer nowTime = DateTimeUtils.getNowTimeStamp();
            if(!(nowTime >= startTime && nowTime < endTime)) {
                return ResultMapHelper.result(ActivityEnums.ACTIVITY_OVER);
            }
            //Integer userId = Integer.parseInt(baseReDto.getUserId());
            BmsUser bmsUser = TokenManager.getUser(userId);
            if(bmsUser == null){
                return ResultMapHelper.result(ResultCode.USER_TOKEN_INVALID, ResultMsg.CODE_USER_NO_EXIST);
            }
            if(StringUtils.isBlank(bmsUser.getPhone())){
                return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_NO_BIND, ResultMsg.MSG_USER_PHONE_NO_BIND);
            }
            BmsDxClientRole bmsDxClientRole = bmsDxClientRoleService.getUserClientRole(userId,Constants.GENERAL_USER_ROLE_ID);
            Integer registerTime = DateTimeUtils.converDateToInterger(bmsDxClientRole.getNewTime());
            if(registerTime >= startTime && registerTime < endTime) {
                isFirstLogin = Constants.COMMON_FLAG_TRUE_INT;
            }
            BmsUserOverMeal bmsUserOverMeal = bmsUserOverMealDao.findByUserId(userId);
            if(bmsUserOverMeal == null){
                bmsUserOverMeal = new BmsUserOverMeal();
                bmsUserOverMeal.setUserId(userId);
                bmsUserOverMeal.setHaveNum(Integer.parseInt(redisTemplate.opsForValue().get(Constants.REDIS_KEY_OVER_MEAL_SNUM).toString()));
                bmsUserOverMeal.setNewTime(nowDate);
                bmsUserOverMealDao.save(bmsUserOverMeal);
            }
            //判断是否有抽奖次数
            if((bmsUserOverMeal.getHaveNum() > 0 && bmsUserOverMeal.getTodayNum() > 0) || bmsUserOverMeal.getExtraNum() > 0){
                if(bmsUserOverMeal.getTodayNum() > 0) {
                    bmsUserOverMeal.setTodayNum(bmsUserOverMeal.getTodayNum() - 1);
                    bmsUserOverMeal.setHaveNum(bmsUserOverMeal.getHaveNum() - 1);
                    bmsUserOverMeal.setHaveUpdateTime(nowDate);
                }else {
                    bmsUserOverMeal.setExtraNum(bmsUserOverMeal.getExtraNum() - 1);
                    //bmsUserOverMeal.setExtraUpdateTime(nowDate);
                }
                //TODO 开始抽奖
                Integer count = 0;
                while (count < 100) {
                    count++;
                    List<BmsMealPrize> bmsMealPrizes = bmsMealPrizeService.findAllPrizes();
                    //bmsMealPrizes = handleMealPrizeRemainZero(bmsMealPrizes);
                    if(!(isFirstLogin != null && isFirstLogin == Constants.COMMON_FLAG_TRUE_INT)){
                        //如果是老用户，将8元和5元的概率用2元替换
                        bmsMealPrizes = removeEightAndFiveCoupon(bmsMealPrizes);
                    }
                    if (!(bmsMealPrizes != null && bmsMealPrizes.size() > 0)) {
                        return ResultMapHelper.result(ActivityEnums.SYS_DELAY);
                    }
                    List<Double> orignalRates = new ArrayList<>();
                    for (BmsMealPrize bmsMealPrize : bmsMealPrizes) {
                        double probability = bmsMealPrize.getProbability();
                        if (probability < 0) {
                            probability = 0;
                        }
                        orignalRates.add(probability);
                    }
                    int orignalIndex = LotteryUtil.lottery(orignalRates);
                    if (bmsMealPrizes.size() > orignalIndex) {
                        BmsMealPrize bmsMealPrize = bmsMealPrizes.get(orignalIndex);
                        if (bmsMealPrize != null && bmsMealPrize.getRemainNum() > 0) {
                            if(!(bmsMealPrize.getRemainNum() > 0)){
                                continue;
                            }
                            //是否在黑名单
                            if(checkIsBlackUser(userId,bmsMealPrize)){
                                continue;
                            }
                            //用户是否抽中过当前券，如果是霸王餐或者8元代金券也不能再抽了
                            if (checkIsLimitPrize(userId, bmsMealPrize)) {
                                continue;
                            }
                            //更新库存
                            boolean isCanGet = false;
                            Integer updateRow;
                            while (true) {
                                updateRow = bmsMealPrizeService.getBaseDao().updateRemainNum(bmsMealPrize.getId(), bmsMealPrize.getUpdateNumVersion());
                                if(updateRow == 1){
                                    isCanGet = true;
                                    break;
                                }
                                entityManager.unwrap(Session.class).evict(bmsMealPrize);
                                bmsMealPrize = bmsMealPrizeService.findPrizeById(bmsMealPrize.getId());
                                if(bmsMealPrize.getRemainNum() <= 0){
                                    break;
                                }
                            }
                            if (isCanGet) {
                                //执行真正的抽奖逻辑
                                BmsUserReceCoupon bmsUserReceCoupon = new BmsUserReceCoupon();
                                bmsUserReceCoupon.setUserId(userId);
                                bmsUserReceCoupon.setType(bmsMealPrize.getType());
                                bmsUserReceCoupon.setNewTime(nowDate);
                                if (bmsMealPrize.getType() == Constants.DAIJIN_COUPON) {
                                    bmsUserReceCoupon.setBusinessId(bmsMealPrize.getBmsFullCoupon().getBusinessId());
                                    bmsUserReceCoupon.setFullCouponId(bmsMealPrize.getBmsFullCoupon().getId());
                                    bmsUserReceCoupon.setExpireTime(DateTimeUtils.addMonth(bmsUserReceCoupon.getNewTime(), 1));
                                    bmsUserReceCoupon.setBmsFullCoupon(bmsMealPrize.getBmsFullCoupon());
                                } else if (bmsMealPrize.getType() == Constants.FLI_COUPON) {
                                    bmsUserReceCoupon.setBusinessId(bmsMealPrize.getBmsBusinessCoupon().getBusinessId());
                                    bmsUserReceCoupon.setBusinessCouponId(bmsMealPrize.getBmsBusinessCoupon().getId());
                                    bmsUserReceCoupon.setExpireTime(DateTimeUtils.addMonth(bmsUserReceCoupon.getNewTime(), 1));
                                    bmsUserReceCoupon.setBmsBusinessCoupon(bmsMealPrize.getBmsBusinessCoupon());
                                    bmsUserReceCoupon.setConsumerCode(OrderUtils.getGroupBuyPayNo(false));
                                }
                                bmsUserReceCoupon.setStatus(Constants.COMMON_FLAG_FALSE_INT);
                                this.doHandleWinning(bmsUserOverMeal,bmsMealPrize, bmsUserReceCoupon);
                                List<BmsUserReceCoupon> bmsUserReceCoupons = new LinkedList<>();
                                bmsUserReceCoupons.add(bmsUserReceCoupon);
                                bmsUserReceCouponService.setBmsUserReceCoupon(bmsUserReceCoupons);
                                Map<String,Object> resultMap = new HashMap<>();
                                resultMap.put("userReceCoupon",bmsUserReceCoupon);
                                UserReceRpDto userReceRpDto = handleCleanData(bmsUserReceCoupon);
                                resultMap.put("bmsBusiness",userReceRpDto);
                                Map<String,Object> userData = new HashMap<>();
                                userData.put("shareUrl",JSON.parseObject(bmsDxConfigService.getConfigByCode(BmsDxConfigService.MEAL_CODE)).get("shareUrl"));
                                userData.put("isCanShare",handleUserCanShare(bmsUserOverMeal,nowTime));
                                resultMap.put("config", bmsDxConfigService.getConfigByCode(BmsDxConfigService.MEAL_CODE));
                                return ResultMapHelper.success(resultMap,userData,ResultMsg.MSG_GET_SUCCESS);
                            }
                        }
                    }
                }
                return ResultMapHelper.result(ActivityEnums.SYS_DELAY);
            }else {
                //没有抽奖次数判断能否助力
                if(bmsUserOverMeal.getExtraUpdateTime() == null ||
                        DateTimeUtils.converDateToInterger(DateTimeUtils.getEndTimeOfDay(bmsUserOverMeal.getExtraUpdateTime())) < nowTime){
                    return ResultMapHelper.result(ActivityEnums.CAN_HELP);
                }
                //最终不能助力，今日抽奖次数已用完
                return ResultMapHelper.result(ActivityEnums.NO_USE);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally {
            RedisTemplateUtils.releaseLock(redisKey);
        }
        return ResultMapHelper.result(ActivityEnums.SYS_DELAY);
    }

    private Integer handleUserCanShare(BmsUserOverMeal bmsUserOverMeal,Integer nowTime) {
        //没有抽奖次数判断能否助力
        Integer ret = Constants.COMMON_FLAG_FALSE_INT;
        if(bmsUserOverMeal.getExtraUpdateTime() == null ||
                DateTimeUtils.converDateToInterger(DateTimeUtils.getEndTimeOfDay(bmsUserOverMeal.getExtraUpdateTime())) < nowTime){
            ret = Constants.COMMON_FLAG_TRUE_INT;
        }
        return ret;
    }

    private List<BmsMealPrize> handleMealPrizeRemainZero(List<BmsMealPrize> bmsMealPrizes) {
        //找出2元概率
        BmsMealPrize towBmsMealPrize = null;
        for(BmsMealPrize bm : bmsMealPrizes){
            if(bm.getType() == Constants.DAIJIN_COUPON){
                BmsFullCoupon bmsFullCoupon = bm.getBmsFullCoupon();
                String[] fullRule = bmsFullCoupon.getFullRule().split("_");
                Integer money = Integer.parseInt(fullRule[1]);
                if(!(money == eightCoupon || money == fiveCoupon)){
                    towBmsMealPrize = bm;
                    break;
                }
            }
        }
        List<BmsMealPrize> bmsMealPrizeList = new ArrayList<>();
        for(int index = 0;index < bmsMealPrizes.size();index++){
            BmsMealPrize bmsMealPrize = bmsMealPrizes.get(index);
            if(bmsMealPrize.getRemainNum() <= 0){
                BmsMealPrize newBto = new BmsMealPrize();
                BeanUtils.copyProperties(towBmsMealPrize,newBto);
                newBto.setProbability(bmsMealPrize.getProbability());
                bmsMealPrizeList.add(newBto);
            }else {
                bmsMealPrizeList.add(bmsMealPrize);
            }
        }
        return bmsMealPrizeList;
    }

    private List<BmsMealPrize> removeEightAndFiveCoupon(List<BmsMealPrize> bmsMealPrizes) {
        //找出2元概率
        BmsMealPrize towBmsMealPrize = null;
        for(BmsMealPrize bm : bmsMealPrizes){
            if(bm.getType() == Constants.DAIJIN_COUPON){
                BmsFullCoupon bmsFullCoupon = bm.getBmsFullCoupon();
                String[] fullRule = bmsFullCoupon.getFullRule().split("_");
                Integer money = Integer.parseInt(fullRule[1]);
                if(!(money == eightCoupon || money == fiveCoupon)){
                    towBmsMealPrize = bm;
                    break;
                }
            }
        }
        List<BmsMealPrize> bmsMealPrizeList = new LinkedList<>();
        for(int index = 0;index < bmsMealPrizes.size();index++){
            BmsMealPrize bmsMealPrize = bmsMealPrizes.get(index);
            if(bmsMealPrize.getType() == Constants.FLI_COUPON){
                bmsMealPrizeList.add(bmsMealPrize);
            }else if(bmsMealPrize.getType() == Constants.DAIJIN_COUPON){
                BmsFullCoupon bmsFullCoupon = bmsMealPrize.getBmsFullCoupon();
                String[] fullRule = bmsFullCoupon.getFullRule().split("_");
                Integer money = Integer.parseInt(fullRule[1]);
                if(money == eightCoupon || money == fiveCoupon){
                    BmsMealPrize newBto = new BmsMealPrize();
                    BeanUtils.copyProperties(towBmsMealPrize,newBto);
                    newBto.setProbability(bmsMealPrize.getProbability());
                    bmsMealPrizeList.add(newBto);
                }else {
                    bmsMealPrizeList.add(bmsMealPrize);
                }
            }
        }
        return bmsMealPrizeList;
    }

    private boolean checkIsBlackUser(Integer userId,BmsMealPrize bmsMealPrize) {
        boolean ret = false;
        BmsUserBlacklist bmsUserBlacklist = bmsUserBlacklistService.getBaseDao().findByUserId(userId);
        if(bmsUserBlacklist != null){
            //判断是否是霸王餐券
            if(bmsMealPrize.getType() == Constants.FLI_COUPON){
                ret = true;
            }else if(bmsMealPrize.getType() == Constants.DAIJIN_COUPON){
                BmsFullCoupon bmsFullCoupon = bmsMealPrize.getBmsFullCoupon();
                String[] fullMoneys = bmsFullCoupon.getFullRule().split("_");
                Integer fullMoney = Integer.parseInt(fullMoneys[1]);
                if(fullMoney == eightCoupon || fullMoney == fiveCoupon){
                    ret = true;
                }
            }
        }
        return ret;
    }

    private boolean checkIsNewUser(Integer isFirstLogin, BmsMealPrize bmsMealPrize) {
        boolean ret = false;
        if(!(isFirstLogin != null && isFirstLogin == Constants.COMMON_FLAG_TRUE_INT)){
            //判断是否是8元还是5元
            if(bmsMealPrize.getType() == Constants.DAIJIN_COUPON){
                //List<BmsFullCoupon> bmsFullCoupons = bmsFullCouponService.findUserGetDaiJinCoupon(userId,bmsMealPrize.getFullCouponId());
                BmsFullCoupon bmsFullCoupon = bmsMealPrize.getBmsFullCoupon();
                String[] fullMoneys = bmsFullCoupon.getFullRule().split("_");
                Integer fullMoney = Integer.parseInt(fullMoneys[1]);
                if(fullMoney == eightCoupon || fullMoney == fiveCoupon){
                    ret = true;
                }
            }
        }
        return ret;
    }

    private UserReceRpDto handleCleanData(BmsUserReceCoupon bmsUserReceCoupon) {
        UserReceRpDto userReceRpDto = new UserReceRpDto();
        userReceRpDto.setType(bmsUserReceCoupon.getType());
        if(bmsUserReceCoupon.getType() == Constants.FLI_COUPON) {
            userReceRpDto.setVendorName(bmsUserReceCoupon.getBmsBusinessCoupon().getBmsBusiness().getVendorName());
            userReceRpDto.setCouponName(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponName());
        }else if(bmsUserReceCoupon.getType() == Constants.DAIJIN_COUPON){
            userReceRpDto.setCouponName(bmsUserReceCoupon.getBmsFullCoupon().getCouponName());
            userReceRpDto.setCouponMoney(bmsUserReceCoupon.getBmsFullCoupon().getFullRule());
        }
        userReceRpDto.setNum(Constants.COMMON_FLAG_TRUE_INT);
        return userReceRpDto;
    }

    @Transactional
    public void doHandleWinning(BmsUserOverMeal bmsUserOverMeal,BmsMealPrize bmsMealPrize, BmsUserReceCoupon bmsUserReceCoupon) {
        bmsUserReceCouponService.getBaseDao().save(bmsUserReceCoupon);
        bmsVerRecordService.addRecordByReceQuan(bmsUserReceCoupon);
        //保存抽奖记录
        bmsMealPrizeRecordService.addUserPrizeRecord(bmsUserReceCoupon.getUserId(),bmsMealPrize);
        bmsUserOverMealDao.save(bmsUserOverMeal);
    }

    /**
     * @Description 校验是否是特殊的两种（霸王餐，8元代金券）
     * @Param:
     * @return:
     * @Author: cfx
     * @Date: 2019/12/16
     */
    private boolean checkIsLimitPrize(Integer userId,BmsMealPrize bmsMealPrize) {
        boolean ret = false;
        if(bmsMealPrize.getType() == Constants.DAIJIN_COUPON){
            //List<BmsFullCoupon> bmsFullCoupons = bmsFullCouponService.findUserGetDaiJinCoupon(userId,bmsMealPrize.getFullCouponId());
            BmsFullCoupon bmsFullCoupon = bmsMealPrize.getBmsFullCoupon();
            String[] fullMoneys = bmsFullCoupon.getFullRule().split("_");
            Integer fullMoney = Integer.parseInt(fullMoneys[1]);
            if(fullMoney == eightCoupon){
                //判断用户是否已经领取过8元代金券
                List<BmsMealPrizeRecord> bmsMealPrizeRecords = bmsMealPrizeRecordService.findUserGetCoupon(userId,bmsMealPrize.getType());
                if(bmsMealPrizeRecords != null && bmsMealPrizeRecords.size() > 0){
                    Set<Integer> bmsFullCouponIds = bmsMealPrizeRecords.stream().map(BmsMealPrizeRecord::getFullCouponId).collect(Collectors.toSet());
                    List<BmsFullCoupon> bmsFullCoupons = bmsFullCouponService.findByIds(bmsFullCouponIds);
                    if(bmsFullCoupons != null && bmsFullCoupons.size() > 0){
                        for(BmsFullCoupon bs : bmsFullCoupons){
                            if(bs.getFullType() == Constants.FULL_RULE_ALL){
                                String[] bsFullMoneys = bs.getFullRule().split("_");
                                Integer bsFullMoney = Integer.parseInt(bsFullMoneys[1]);
                                if(bsFullMoney == eightCoupon){
                                    ret = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }else if(bmsMealPrize.getType() == Constants.FLI_COUPON){
            //判断用户是否抽过霸王餐
            List<BmsMealPrizeRecord> bmsMealPrizeRecords = bmsMealPrizeRecordService.findUserGetCoupon(userId,Constants.FLI_COUPON);
            if(bmsMealPrizeRecords != null && bmsMealPrizeRecords.size() > 0){
                ret = true;
            }
        }
        return ret;
    }

    @Override
    @Transactional
    public Map<String, Object> userHelp(ParamsMap paramsMap) {
        synchronized (userHelp) {
            if(!redisTemplate.hasKey(Constants.REDIS_KEY_OVER_MEAL_OPEN)){
                return ResultMapHelper.result(ActivityEnums.ACTIVITY_CLOSE);
            }
            String activityTime = redisTemplate.opsForValue().get(Constants.REDIS_KEY_OVER_MEAL_OPEN).toString();
            String[] startEndTime = activityTime.split(",");
            Integer startTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[0],DateTimeUtils.DATE_PATTERN_DAY_08));
            Integer endTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[1],DateTimeUtils.DATE_PATTERN_DAY_08));
            Integer nowTime = DateTimeUtils.getNowTimeStamp();
            if(!(nowTime >= startTime && nowTime < endTime)) {
                return ResultMapHelper.result(ActivityEnums.ACTIVITY_CLOSE);
            }
            String userIds = paramsMap.getString("userId");
            String[] tUser = userIds.split("\\?");
            Integer userId = Integer.parseInt(tUser[0]);
            //查询用户今天是否可助力
            BmsUserOverMeal bmsUserOverMeal = bmsUserOverMealDao.findByUserId(userId);
            Date nowDate = new Date();
            if(bmsUserOverMeal == null){
                return ResultMapHelper.result(ActivityEnums.ACTIVITY_LINE_FAIL);
            }
            if(bmsUserOverMeal.getExtraUpdateTime() == null ||
                    DateTimeUtils.converDateToInterger(DateTimeUtils.getEndTimeOfDay(bmsUserOverMeal.getExtraUpdateTime())) < nowTime){
                //助力一次
                if(bmsUserOverMeal.getExtraNum() == null){
                    bmsUserOverMeal.setExtraNum(0);
                }
                bmsUserOverMeal.setExtraNum(bmsUserOverMeal.getExtraNum() + 1);
                bmsUserOverMeal.setExtraUpdateTime(nowDate);
                bmsUserOverMealDao.save(bmsUserOverMeal);
                bmsMealUserHelpService.addUserHelpRecord(bmsUserOverMeal);
                return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
            }
            return ResultMapHelper.result(ActivityEnums.HELP_MAX);
        }
    }

    @Override
    public Map<String, Object> userHelpRecord(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        List<BmsMealUserHelp> bmsMealUserHelps = bmsMealUserHelpService.getBaseDao().findByUserId(userId);
        return ResultMapHelper.success(bmsMealUserHelps,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> userHaveHum(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("haveNum",userId == null ? 0 : this.findUserHaveNum(userId));
        return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
    }
}
